//
//  CircleTransitioner.m
//  CIrcleChangeTransition
//
//  Created by Chenbo on 16/6/29.
//  Copyright © 2016年 北京数字天域科技有限公司. All rights reserved.
//

#import "CircleTransitioner.h"
#import "ViewController.h"

@interface CircleTransitioner ()

@property (weak, nonatomic) id transitionContext;

@end

@implementation CircleTransitioner

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    return 0.5;
}

- (void) animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    self.transitionContext = transitionContext;
    ViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *container = [transitionContext containerView];
    
    UIButton *btn = fromVC.firstBtn;
    UIBezierPath *originPath = [UIBezierPath bezierPathWithOvalInRect:btn.frame];
    CGPoint extremePoint = CGPointMake(btn.center.x - 0, btn.center.y);
    
    float radius = sqrtf(extremePoint.x * extremePoint.x + extremePoint.y * extremePoint.y);
    UIBezierPath *finalPath = [UIBezierPath bezierPathWithOvalInRect:CGRectInset(btn.frame, -radius, -radius)];
   
    CAShapeLayer *transitionLayer = [CAShapeLayer layer];
    
    if(_presenting){
        [container addSubview:toVC.view];
        transitionLayer.path = finalPath.CGPath;
        toVC.view.layer.mask = transitionLayer;
    }else{
        [container insertSubview:toVC.view belowSubview:fromVC.view];
        transitionLayer.path = originPath.CGPath;
        fromVC.view.layer.mask = transitionLayer;
    }
    CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"path"];
    if (_presenting){//present
        animation.fromValue = (__bridge id _Nullable)(originPath.CGPath);
        animation.toValue = (__bridge id _Nullable)(finalPath.CGPath);
    }else{
        
        animation.fromValue = (__bridge id _Nullable)(finalPath.CGPath);
        animation.toValue = (__bridge id _Nullable)(originPath.CGPath);
    }
    animation.duration = [self transitionDuration:transitionContext];
    animation.delegate = self;
    [transitionLayer addAnimation:animation forKey:@""];
    
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    [self.transitionContext completeTransition:YES];//![self.transitionContext transitionWasCancelled]
//    [self.transitionContext viewControllerForKey:UITransitionContextToViewControllerKey].view.layer.mask = nil;
    [self.transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey].view.layer.mask = nil;
    
}


@end
